﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using devtm.Editor.TypeSelector.AttributeBuilder;

namespace devtm.Editor.TypeSelector
{
    /// <summary>
    /// Interaction logic for UserControl1.xaml
    /// </summary>
    public partial class ObjectViewer : UserControl, IDisposable
    {


        public ObjectViewer()
        {
            InitializeComponent();
            this.DataContext = new ContextAttributeBuilder();
            Context.CollectionChanged += Context_CollectionChanged;
        }


        void Context_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {

            if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add)
            {

                foreach (var item in e.NewItems)
                {
                    (item as TreeViewItem).ExpandSubtree();
                    treeView1.Items.Add(item);
                }

            }
            else if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Remove)
            {
                foreach (var item in e.OldItems)
                    treeView1.Items.Remove(item);
            }
        }

        public ContextAttributeBuilder Context
        {
            get { return (ContextAttributeBuilder)this.DataContext; }
        }


        public void Dispose()
        {
            Dispose(true);
        }

        public void Dispose(bool disposing)
        {
            try
            {
                if (!disposing)
                    if (this.DataContext != null)
                        Context.CollectionChanged -= Context_CollectionChanged;
            }
            catch (Exception)
            {


            }


        }

        ~ObjectViewer()
        {
            Dispose(false);
        }



        internal System.Xml.Linq.XElement Serialize()
        {
            return (this.DataContext as ContextAttributeBuilder).Serialize();
        }

        internal void UnSerialize(System.Xml.Linq.XElement node)
        {
            (this.DataContext as ContextAttributeBuilder).UnSerialize(node);
        }

        public bool SelectType<T>(T attribute) 
            where T : Attribute
        {
            bool ret = (this.DataContext as ContextAttributeBuilder).SelectType(attribute);
            return ret;
        }

    }
}
